var Inject = (function () {
    var _this = {};
    var _video = {};
    var _tabId = 0;

    _this.init = function () {
        var nodes = document.getElementById('J_prismPlayer').childNodes
        _video = nodes[0]

        if (_video.paused) {
            _this.play()
        }

        _video.addEventListener('play', function() {
            _this.tell('P', '视频开始播放');
        })
        
        _video.addEventListener('pause', function() {
            // _this.tell('S', '视频播放暂停，请处理'); // 验证码与人脸识别导致的暂停已在background.js处理
        })
        
        _video.addEventListener('ended', function() {
            _this.tell('D', '视频播放结束，3秒后自动播放下一章节');
            var nextDom = document.getElementsByClassName('next_button___YGZWZ');
            nextDom[0].click()
            _this.play();
        })
        
        _video.addEventListener('error', function() {
            _this.tell('E', '视频播放出错，自动处理');
            location.reload(); //刷新网页 自动播放
            _this.play();
        })
        
        window.onhashchange = function () {
            _this.tell('N', '切换新章节，3秒后自动播放..')
            _this.play();
        }

        // listen to the Control Center (background.js) messages
        chrome.extension.onMessage.addListener(backgroundMessageHandle);
    };

    // messages coming from "background.js"
    function backgroundMessageHandle(request, sender, sendResponse) {
        if (request.message == 'tabId') {
            _tabId = request.data.tabId
        }
    };

    _this.tell = function(tip, msg) {
        var msg = msg || {};
        chrome.extension.sendRequest({
            tip: tip,
            msg: msg
        });
    };

    _this.play = function(){
        setTimeout(() => {
            var nodes = document.getElementById('J_prismPlayer').childNodes
            _video = nodes[0]
            _video.setAttribute('muted', 'muted');
            // _video.play();

            var playButton = document.getElementsByClassName('outter')[0];
            playButton.click();

        }, 3000);
    }

    return _this;
}());

window.addEventListener("load", function () {
    setTimeout(() => {
        Inject.init();
    }, 5000);
    
}, false);